package com.gateway.plugin.security.oauth2.extract;

import com.gateway.common.constant.ContextConstants;
import com.gateway.common.enums.AuthenticationTypeEnum;
import com.gateway.plugin.security.oauth2.client.OAuth2Client;
import com.gateway.security.common.authentication.client.ClientAuthenticationToken;
import com.gateway.security.common.authentication.client.ClientPrincipal;
import com.gateway.security.common.extract.ClientExtractor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/12 11:40
 **/
public class OAuth2Extractor implements ClientExtractor {
    private static final String BEARER = "Bearer ";

    @Override
    public ServerWebExchange extract(ServerWebExchange exchange, ClientAuthenticationToken token) {
        ServerHttpRequest.Builder mutate = exchange.getRequest().mutate();
        ClientPrincipal principal = token.getPrincipal();
        if (principal instanceof OAuth2Client oAuth2Client) {
            mutate.header(ContextConstants.CTX_KEY_CLIENT_ID, oAuth2Client.getClientId());
            mutate.header(ContextConstants.CTX_KEY_CLIENT_NAME, URLEncoder.encode(oAuth2Client.getName(), StandardCharsets.UTF_8));
        }
        mutate.header(HttpHeaders.AUTHORIZATION, BEARER + token.getToken().getToken());
        return exchange.mutate().request(mutate.build()).build();
    }
}
